package com.example.netty.netty.privateChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
    //私聊的channel管理
    private static HashMap<String,Channel> channelMap = new HashMap<>();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    //与handler建立连接时触发
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //将该通道加入管理列表
        channelMap.put(ctx.channel().remoteAddress().toString(), ctx.channel());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(dateFormat.format(new Date())+ctx.channel().remoteAddress()+" 上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(dateFormat.format(new Date())+ctx.channel().remoteAddress()+" 下线了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //发送的消息格式：\127.0.0.1:61782-hello
        String[] split = s.split("-");
        Channel channel = channelHandlerContext.channel();

        channelMap.get(split[0]).writeAndFlush(dateFormat.format(new Date())+"-客户端："
                + channel.remoteAddress() + " 说：" + split[1] + "\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        cause.printStackTrace();
        ctx.close();
    }
}











